--[[
Author: wangxiaoyan
Date: 2020-09-27 21:01:25
LastEditTime: 2020-11-11 21:43:58
FilePath: \Lua\View\PopUI\UISevenChallenge.lua

七日挑战（新手挑战）
--]]

require 'View/UIBase/UIBase'

UISevenChallenge = UIBase.New(PanelResNames.UISevenChallenge)
local _M = UISevenChallenge

_M.SEVENDAY = table.getn(G.dataTable["t_newcomerchallenge"])
_M.SHOP_ID = 4000

function _M.Init(func, id)
    UISevenChallenge.activeId = id;
    UIBase.Init(_M,func)
end

-- 创建回调
function _M:OnCreate()
    self.selectDay = 1
    self.taskData = nil
    self.ContentItems = {}
    self.ToggleContentItems = {}
    self.boxProgress = self:GetChild("fill");
    self.totalTaskInfo = self:GetChild("TotaltaskInfo");
    self.surpTimeLab = self:GetChild("surpTimeLab")
    self.rewardTimeLab = self:GetChild("rewardTimeLab")
    --self.Resbar = self:GetChild("Resbar")
    self.toggleController = self:GetController("toggleController")
    --self.showOpen = self.fguiObj:GetTransition("t0");
    self.dynamicList = self:SetDynamicList(self:GetChild("dynamicList"),self.RefreshDynamicItem,nil, true);
    self.toggleDynamicList = self:SetDynamicList(self:GetChild("toggleDynamicList"),self.RefreshToggleDynamicItem,nil, true)
    --self.costData = logicMgr.ShopManager.returnShopGold(self.SHOP_ID)[1];
  --  滑动条7个奖励
    self.boxReward = {}
    for i = 1, 7 do
        local singleBox = self:GetChild("Node" .. tostring(i))
        table.insert(self.boxReward, singleBox);
    end


    self:RegisterOnClick(self:GetChild("back"),self.OnBack)
    self:RegisterOnClick(self:GetChild("bgClose"),self.OnBack)
    --self:RegisterOnClick(self:GetChild("shop"),self.ClickShop)
    self:RegisterEvent(Config.EventType.Res_TaskInfo_Get,self.Refresh);
    self:RegisterEvent(Config.EventType.Fresh_TaskInfo,self.RefreshBox);
    --self:RegisterEvent(Config.EventType.Fresh_Currency,self.updateCost);
end

-- 显示
function _M:OnEnable()
    if self.activeId == nil then
        self:OnBack();
    else
        self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil then
            self:OnBack();
            return ;
        end
        self.curDay = logicMgr.ActiveManager.getActiveBeginDay(self.serverData.startTime);
        self.selectDay = math.min(self.curDay, self.SEVENDAY);
        self:Refresh();
    end
    --local surpDay = self:GetSurpDayAndHour(self.SEVENDAY)
    --self.activeData = {};
    --self.activeData.endTime = 0;
    --self.activeData.collectTime = 0;
    --if self.activeId ~= nil then
    --    local data = logicMgr.ActiveManager.getActiveEntranceDataById(self.activeId);
    --    if data ~= nil then
    --        self.activeData = data;
    --    end
    --end
    --self.curDay = self.SEVENDAY - surpDay
    --if self.curDay <= 0 then
    --    self.curDay = 1
    --end
    

end


function _M:Refresh()
    
    self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
    if self.serverData == nil then
        self:OnBack();
        return ;
    end
    local time = HelperFunc.GetServerTime();
    self.endCountDown = self.serverData.endTime - time;
    self.collectCountDown = self.serverData.drawEndTime - time;
    self:updataActiveCountDown();
    --self:SetIcon(self.Resbar:GetChild("icon"), self.costData.currencyIcon)
    self:updateCost();
    self:TimeCall(self.updataActiveCountDown, 1000, -1);

    local curData = G.dataTable["t_newcomerchallenge"][tostring(self.selectDay)]
    self.taskData = decodeJsonStrToTabel(curData.f_TaskId)
    if self.taskData then
        if type(self.taskData) =="table" and #self.taskData > 0 then
            table.sort(self.taskData,function(a,b)
                local taskA = taskInfoHandler.GetTaskInfo(a)
                local taskB = taskInfoHandler.GetTaskInfo(b)
                if taskA.status > taskB.status then return true end;
                if taskA.status < taskB.status then return false end;
                return a < b;
            end)
            self.dynamicList.numItems = #self.taskData
            self.toggleDynamicList.numItems = self.SEVENDAY
            HelperFunc.ListTranstionPlay(self.dynamicList,function()
                self.toggleDynamicList:ScrollToView(self.selectDay - 1, true);
            end)
            self.toggleController.selectedIndex = 1
            self.toggleController.selectedIndex = self.selectDay - 1
        end
    end
    self:RefreshBox();
end

_M.assembleTaskBoxConfig = {};
_M.boxMaxCount = 100;
function _M:RefreshBox()
    
    if #_M.assembleTaskBoxConfig == 0 then
        local taskbox= G.dataTable["t_taskbox"];
        
        for key, value in pairs(taskbox) do
            if value.f_BoxType==6 then
                table.insert( _M.assembleTaskBoxConfig,value);   
            end
        end

        table.sort(_M.assembleTaskBoxConfig, function(a, b)
            return a.f_NeedExpCount < b.f_NeedExpCount
        end);
        _M.boxStatus = {}
        _M.boxRewardItem = {}
        for i = 1, #self.boxReward do
            local boxConfig = _M.assembleTaskBoxConfig[i];
            local tempNum = _M.boxReward[i]:GetChild("num");
            local Tips = _M.boxReward[i]:GetChild("Tips");
            -- if i == 1 then
            --     _M.firstBoxCount = boxConfig.f_NeedExpCount;
            -- end
            if tonumber(_M.boxMaxCount) < tonumber(boxConfig.f_NeedExpCount) then
                _M.boxMaxCount = boxConfig.f_NeedExpCount;
            end
            Tips.text=boxConfig.f_NeedExpCount;
            tempNum.text = getLanguage("loginaward_1060"..i);
            local statusController = _M.boxReward[i]:GetController("status");
            statusController.selectedIndex = 0;
            table.insert(_M.boxStatus, statusController);
            table.insert(_M.boxRewardItem, _M.boxReward[i]:GetChild("item"));
            --table.insert(_M.boxRewardItemCtrl, CtrlManager.GetCtrl(PanelNames.Item));
        end
    end
    
    --当前分数
    local score =  logicMgr.TaskManager.getTaskLivenessServerData(6)["liveness"];
    if score == nil then
        score = 0;
    end
    
    for i = 1, #self.boxReward do
        -- body
        local taskBoxConfig = _M.assembleTaskBoxConfig[i];
        local rewards;
        rewards = decodeJsonStrToTabel(taskBoxConfig.f_BoxAward);

        if #rewards > 0 and _M.boxRewardItem[i] ~= nil then
            _M.boxRewardItem[i].onClick:Clear();
            self.boxReward[i].visible = true;
            local v=nil;
            if i==#self.boxReward then
               v= _M.boxReward[i]:GetChild("Itemnum").scale ;
            end
            logicMgr.CostManager.RefreshItem(_M.boxRewardItem[i], rewards[1], {isShowBigNum = true});
            if i==#self.boxReward then
                _M.boxRewardItem[i]:GetChild("num").scale = Vector3(v.x,v.y,1)
            end
                local thisboxinfo = logicMgr.TaskManager.getTaskLivenessBoxServerData(taskBoxConfig.f_BoxID);
                
                if thisboxinfo["reward"] == -1 then
                    if _M.boxStatus[i] ~= nil then
                        _M.boxStatus[i].selectedIndex = 2;
                    end
                elseif thisboxinfo["reward"] == 0 then
                        -- body
                        if _M.boxStatus[i] ~= nil then
                            _M.boxStatus[i].selectedIndex = 0;
                        end
                elseif thisboxinfo["reward"] == 1 then
                    -- body
                    if _M.boxStatus[i] ~= nil then
                        _M.boxStatus[i].selectedIndex = 1;
                    end
                    _M.boxRewardItem[i].onClick:Clear();
                    _M.boxRewardItem[i].onClick:Add(function ()
                        taskInfoHandler.SendReqLivenessInfo(taskBoxConfig.f_BoxID);
                    end);
           --  end
            end
        end


     
    end

  --给分数赋值
  self.totalTaskInfo.text = tostring(score);
  self.boxProgress.value = math.min(tonumber(score), tonumber(_M.boxMaxCount));

end

function _M:updataActiveCountDown()
    if self.endCountDown == nil or self.collectCountDown == nil then
        return;
    end
    if self.endCountDown <= 0 then
        self.surpTimeLab.text = "已结束";
    else
        self.surpTimeLab.text = HelperFunc.GetSurpTimeStr(self.endCountDown);
    end
    self.endCountDown = self.endCountDown - 1;
    if self.collectCountDown <= 0 then
        self.rewardTimeLab.text = "已无法领取";
    else
        self.rewardTimeLab.text = HelperFunc.GetSurpTimeStr(self.collectCountDown);
    end
    self.collectCountDown = self.collectCountDown - 1;
end

function _M:updateCost()
    --self.Resbar.title = logicMgr.ItemManager.getBagNumByTableID(tonumber(self.costData.currencyId))
end

function _M:CreateDynamicItem(index,itemObj)
    if self.ContentItems[index] then
        return
    end
    local item = _M.TaskItem.New()
    self.ContentItems[index] = item
    item:OnCreate(itemObj,self)
end
function _M:RefreshDynamicItem(index, itemObj)
    self:CreateDynamicItem(index,itemObj)
    self.ContentItems[index]:OnShow(self.taskData[index])
end

function _M:CrateRefreshToggleDynamicItem(index, itemObj)
    if self.ToggleContentItems[index] then 
        return
    end
    self.ToggleContentItems[index] = {}
    local item = self.ToggleContentItems[index]
    item.root = itemObj
    item.toggleController = self:GetController("locktoggle",item.root)
    item.grayDay = self:GetChild("grayDay",item.root)
    item.grayDesc = self:GetChild("grayDesc",item.root)
    item.highDay = self:GetChild("highDay",item.root)
    item.highDesc = self:GetChild("highDesc",item.root)
    item.lockDay = self:GetChild("lockDay",item.root)
    item.lockDesc = self:GetChild("lockDesc",item.root)

    self:RegisterOnClick(item.root,self.ClickDay,self,index)
end
function _M:RefreshToggleDynamicItem(index, itemObj)
    self:CrateRefreshToggleDynamicItem(index, itemObj)

    local item = self.ToggleContentItems[index]
    local dayConfig = G.dataTable["t_newcomerchallenge"][tostring(index)]
    local dayStr = tostring(index)
    local dayDes = getLanguage(dayConfig.f_SubName)
    
    self:SetText(item.grayDay,dayStr)
    self:SetText(item.grayDesc,dayDes)
    self:SetText(item.highDay,dayStr)
    self:SetText(item.highDesc,dayDes)
    self:SetText(item.lockDay,dayStr)
    self:SetText(item.lockDesc,dayDes)

    item.toggleController.selectedIndex = index > self.curDay and 0 or 1
    UIRedDots.addViewListen(PanelNames.UISevenChallenge,"tag"..index, item.root, Config.RedDotsType.SevenChallenge, dayConfig.f_Id);
end

-- 隐藏
function _M:OnDisable()
    if self.ContentItems then 
        for key, value in pairs(self.ContentItems) do
            value:OnHide()
        end
    end
end

-- 卸载
function _M:OnDestroy()
    UIRedDots.removeViewEvent(PanelNames.UISevenChallenge);
    if self.ContentItems then 
        for key, value in pairs(self.ContentItems) do
            value:OnDestroy()
        end
        self.ContentItems = nil
    end

    self.ToggleContentItems = nil
    _M.assembleTaskBoxConfig = {}
    _M.boxMaxCount=0; 
    _M.boxStatus = {}; 
    _M.boxRewardItem = {}; 
end

function _M:ClickDay(day)
    if day > self.curDay then 
        self.toggleController.selectedIndex = self.selectDay - 1
        UISysTips.AddMsg(getLanguage("Sys_MsgLocked"))
        return
    end

    self.selectDay = day
    self:Refresh()
end

function _M:ClickShop()
    showUI(PanelNames.UIShop, _M.SHOP_ID);
end
--
--function _M:GetSurpTime(endDay)
--    return HelperFunc.GetSurpTime(logicMgr.HeroManager.GetRoleInfo().createTime,endDay)
--end
--
--function _M:GetSurpDayAndHour(endDay)
--    local surpTime = self:GetSurpTime(endDay)
--    local surpDay = math.floor(surpTime / 24 / 3600)
--    local surpHour = math.ceil((surpTime - surpDay*24*3600) / 3600)
--    return surpDay , surpHour
--end

-- 任务类
_M.TaskItem = Class("TaskItem",UIComponentInterface)
local _M_T = _M.TaskItem
local data={};
function _M_T:OnCreate(obj,parent)
    self.taskId = 0
    self.parent = parent
    self.fguiObj = obj

    self.itemList = self:GetChild("itemList")
    self.noRewardGo=self:GetChild("noRewardGo");
    self.rewardGo=self:GetChild("rewardGo");
    self.titleLab = self:GetChild("titleLab")
    self.btnState=self:GetController("state");
    self.processLab = self:GetChild("processLab")

    self.parent:RegisterOnClick(self.noRewardGo,self.ClickGoto,self)
    self.parent:RegisterOnClick(self.rewardGo,self.ClickReward,self)
end
function _M_T:OnShow(taskId)
    self.taskId = tostring(taskId)
    self:Refresh()
end

function _M_T:SimplifyNum(num)
    num = tonumber(num);
    if num >= 10000 then
        num = math.floor(num * 0.01);
        return (num * 0.1).."k";
    end
    return num;
end

function _M_T:Refresh()
    local configTable = G.dataTable["t_task"][self.taskId]      -- 本地配置数据
    local taskData = taskInfoHandler.GetTaskInfo(self.taskId)   -- 服务器数据
    local state = taskData.status                               -- 状态：-1：已领取 0 可前往 1 可领取
    self.rewards = decodeJsonStrToTabel(configTable.f_Award)
    data=configTable;
    self.titleLab.text = getLanguage(configTable.f_TaskDesc)
    self.processLab.text = self:SimplifyNum(taskData.progress).."/"..self:SimplifyNum(configTable.f_Progress)

    -- 奖励
    self:SetDynamicList(self.itemList, self.rendererReward,nil, true);
    if tonumber(configTable.f_ExpCount) > 0 then
        self.itemList.numItems = #self.rewards+1;
    else
        self.itemList.numItems = #self.rewards;
    end

    -- local itemCount = #self.itemList
    -- for i = 1, itemCount do
    --     local item = self.itemList[i]
    --     local isShow = i <= rewardCount
    --     if isShow then
    --         --local reward = self.rewards[i]
    --         logicMgr.CostManager.RefreshItem(item, self.rewards[i]);
    --         --local iconPath = G.dataTable.t_item[tostring(reward[1])].f_Icon
    --         --local iconNum = reward[2]
    --         --self:SetItemQuality(item.quality,reward[1])
    --         --self:SetIcon(item.iconSp,iconPath)
    --         --item.numLab.text = tostring(iconNum)
    --     end
      
    --     if item then item.visible = isShow end
    --     if i==2 then
    --         logicMgr.CostManager.RefreshItem(item, liveness);   
    --         -- item.visible=true;
    --     end
    -- end

    -- 按钮状态
    if state==0 then
        if self.parent.endCountDown <= 0 then
            self.btnState.selectedIndex=3;
        else
            self.btnState.selectedIndex=0;
        end
    elseif state==1 then
        self.btnState.selectedIndex=1;
    else
        self.btnState.selectedIndex=2;
    end
end

function _M_T:rendererReward(index, itemObj)
    if index== #self.rewards+1 then
        local liveness={17,10};
        liveness[2]=data.f_ExpCount;
        logicMgr.CostManager.RefreshItem(itemObj, liveness); 
    else
        logicMgr.CostManager.RefreshItem(itemObj, self.rewards[index]); 
    end
end

function _M_T:OnHide()

end
function _M_T:OnDestroy()
    self.itemList = nil
end

function _M_T:ClickGoto(sender)
    local configTable = G.dataTable["t_task"][self.taskId]
    if logicMgr.FuncOpenManager.isOpen(configTable.f_Switchover) then
        closeUI(self.parent._panelName)
        closeUI(PanelNames.UIActivity)
        showUI(PanelNames.UIHeadMenu);
        logicMgr.FuncOpenManager.jump(configTable.f_Switchover)
    else
        UISysTips.AddMsg(getLanguage("FunctionTipsLocked"));
    end
end

function _M_T:ClickReward()
    local rdtr = ReqTaskRewardMessage.New()
    rdtr.taskId = tonumber(self.taskId)
    sendReqMessage(rdtr)
end

return _M